import React, { useEffect, useMemo, useRef, useCallback } from 'react';
import { tableConfig } from './config/table.config';
import { Button, Space, Tag, Popconfirm } from 'antd';
import { receiveFilter, statusFilter } from './dict';
import { state, actions } from './state';
import { observer } from 'mobx-react-lite';
import type { DataType } from './config/interface';

import TableContent from '@/components/TableContent';
import FormModal from '@/components/FormContent';
import FormItems from './FormItems';

const rowSelection = {
  onChange: (selectedRowKeys: React.Key[], selectedRows: DataType[]) => {
    console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
  }
};

const Practice = observer(() => {
  console.log('first======================');
  const { loading, tableList, payload, total } = useMemo(() => state, []);
  const { queryTableList, submit } = useMemo(() => actions, []);

  const formRef = useRef(null);
  const formData = useRef(null);

  // 查询table数据
  useEffect(() => {
    queryTableList();
  }, []);

  const editItem = useCallback((row: DataType) => {
    formData.current = row;
    formRef.current.setOpen(true);
  }, []);
  const addItem = useCallback(() => {
    formData.current = {};
    formRef.current.setOpen(true);
  }, []);
  const onSubmit = useCallback((form: DataType) => {
    submit(form);
    formRef.current.setOpen(false);
  }, []);

  return (
    <>
      <TableContent
        {...tableConfig}
        loading={loading}
        data={tableList}
        page={{
          defaultPageSize: payload.pageSize,
          total,
          onChange: actions.pageChange
        }}
        toolbar={[
          <Button key="add" type="primary" onClick={addItem}>
            新建
          </Button>
        ]}
        rowSelection={rowSelection}
        slot={{
          receiveMode: (row: DataType) => {
            return <Tag color="blue">{receiveFilter(row.receiveMode)}</Tag>;
          },
          status: (row: DataType) => {
            return <Tag color="blue">{statusFilter(row.status)}</Tag>;
          },
          handler: (row: DataType) => {
            return (
              <Space>
                <Button type="primary" onClick={() => editItem(row)}>
                  操作
                </Button>
                <Popconfirm
                  title="确定删除此数据吗？"
                  okText="确定"
                  cancelText="取消"
                  onConfirm={() => actions.delTableItem(row.id)}
                >
                  <Button type="link" size="small">
                    删除
                  </Button>
                </Popconfirm>
              </Space>
            );
          }
        }}
      />
      {useMemo(() => {
        return (
          <FormModal ref={formRef} formData={formData} onSubmit={onSubmit}>
            <FormItems />
          </FormModal>
        );
      }, [])}
    </>
  );
});

export default Practice;
